package utils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @version V1.0
 * @Title: 配置文件处理类
 * @Package
 * @Description:
 * @author: GaleBlade
 * @date:
 */
public class PropertiesUtil {

    private Properties properties = new Properties();

    public PropertiesUtil(String name){
        //配置文件所在目录路径，相对项目根目录，如果是放在根目录下，直接写文件名称就行
        File file = new File(name);
        try {
            properties.load(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //根据key获取值
    public String get(String key){
        return properties.getProperty(key).trim();
    }

    //根据key获取值，值为空则返回defaultValue
    public String get(String key,String defaultValue){
        return properties.getProperty(key, defaultValue);
    }

    public List<String> getAllKeys(){
        List<String> result = new ArrayList<>();
        Enumeration enu2 = properties.propertyNames();
        while(enu2.hasMoreElements()){
            String key = (String)enu2.nextElement();
            result.add(key);
        }
        return result;
    }

    public void set(String key,String value){
        properties.setProperty(key, value);
    }

    public void set(Properties cache,String name){
        try{
            PrintWriter pw = new PrintWriter(new FileWriter(name));
            cache.list(pw);
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void update(Map<String,String> keyValueMap,String name){
        //2.新建一个输入流和输出流,用来读取和写入文件
        OutputStreamWriter writer = null;
        try {
            //4.将需要修改的键值对,或者新增的键值对,写入到properties中(此处与直接追加操作相同)
            writer = new OutputStreamWriter(new FileOutputStream(name), StandardCharsets.UTF_8);
            Properties cache = new Properties();
            for (String key: keyValueMap.keySet()) {
                cache.setProperty(key,keyValueMap.get(key));
            }
            //5.调用properties中的存储方法
            cache.store(writer,"测试数据");
            //6.关闭资源
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
